<template>
    <div class="search_wrapper">
        <div class="search">
          <span class="iconfont">&#xeba5;</span>
          <input class="search-input" v-model="keyword" type="text" placeholder="输入城市名或拼音" />
        </div>
        <div class="search-content" ref="search" v-show="keyword">
          <ul>
            <li class="search-item border-bottom" v-for="item of list" :key="item.id" @click="handleCityClick(item.name, item.id)">
              {{item.name}}
            </li>
            <li class="search-item border-bottom" v-show="hasNoData">
              没有找到匹配数据
            </li>
          </ul>
        </div>
    </div>
</template>

<script>
import BScroll from 'better-scroll'
import { mapState, mapMutations } from 'vuex'
export default {
  name: 'CitySearch',
  props: {
    groupcity: Object
  },
  data () {
    return {
      keyword: '',
      list: [],
      timer: null
    }
  },
  mounted () {
    this.scroll = new BScroll(this.$refs.search, {
      mouseWheel: {
        speed: 20,
        invert: false,
        easeTime: 300
      }
    })
  },
  methods: {
    handleCityClick (city, cityId) {
      this.CHANGE_CITY({ city, cityId })
      // this.$emit('close')
      this.$listeners.close()
    },
    ...mapMutations(['CHANGE_CITY'])
  },
  computed: {
    ...mapState(['city']),

    hasNoData () {
      return !this.list.length
    }
  },
  watch: {
    // 监听城市搜索关键字变化，根据关键字搜索城市
    keyword () {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      if (!this.keyword) {
        this.list = []
        return false
      }
      this.timer = setTimeout(() => {
        const result = []
        for (let i in this.groupcity) {
          this.groupcity[i].forEach((value) => {
            if (value.pinyin.indexOf(this.keyword) === 0 || value.name.indexOf(this.keyword) > -1) {
              result.push(value)
            }
          })
        }
        this.list = result
      }, 100)
    }
  }
}
</script>

<style lang="stylus" scoped>
  .border-bottom
    &:before
      border-color: #ddd
  .search_wrapper
    .search
      height: .88rem
      padding: 0 .1rem
      position: relative
      text-align: center
      background-image: linear-gradient(90deg, #0af, #0085ff)
      .iconfont
        font-size: .3rem
        position: absolute
        top: .23rem
        left: .7rem
      .search-input
        box-sizing: border-box
        width: 90%
        height: .62rem
        padding: 0 .1rem 0 .6rem
        margin-top: .1rem
        line-height: .62rem
        border-radius: .62rem
        color: #666
    .search-content
      z-index: 1
      overflow: hidden
      position: absolute
      top: 1.78rem
      left: 0
      right: 0
      bottom: 1rem
      background: #fff
      .search-item
        line-height: 1rem
        padding-left: .3rem
        background: #fff
        color: #666
        font-size: .28rem
</style>
